from flask import render_template,url_for,request,redirect,flash
from flask_login import login_user,logout_user,login_required
from . import admin
from .forms import AdminLoginForm,AddDeviceForm,ModifyDeviceForm
from ..models import Device,User
from .. import db

@admin.route('/',methods=['GET','POST'])
def index():
    form=AdminLoginForm()
    if form.validate_on_submit():
        user=User.query.filter_by(email=form.email.data).first()
        if user is not None and user.verify_password(form.password.data):
            login_user(user,form.remember_me.data)
            return render_template('admin/base.html')
        flash('您输入的账号或密码有误，请重新输入')
    return render_template('admin/admin_login.html',form=form) 

#添加设备
@admin.route('/addDevice',methods=['GET','POST'])
def addDevice():
    form=AddDeviceForm()
    if form.validate_on_submit():
        devices=Device(device_name=form.device_name.data,
                operator=form.operator.data,
                imei=form.imei.data)
        db.session.add(devices)
        db.session.commit()
        flash('添加设备成功，请继续添加')
        return redirect(url_for('admin.addDevice'))
    return render_template('admin/adddevice.html',form=form)

#设备列表
@admin.route('/devicesList')
def devicesList():
    devices=Device.query.all()
    return render_template('admin/devicesList.html',list=devices)

#删除列表
@admin.route('/deleteDevice')
def deleteDevice():
    id=request.args.get('id')
    device=Device.query.filter_by(id=id).first()
    db.session.delete(device)
    db.session.commit()
    return redirect(url_for('admin.devicesList'))

#修改设备
@admin.route('/modifyDevice',methods=['GET','POST'])
def modifyDevice():
    form=ModifyDeviceForm()
    id=request.args.get('id')
    device=Device.query.filter_by(id=id).first()
    if form.validate_on_submit():
        device.device_name=form.device_name.data
        device.operator=form.operator.data,
        device.imei=form.imei.data
        db.session.add(device)
        db.session.commit()
        return redirect(url_for('admin.devicesList'))
    form.device_name.data=device.device_name
    form.operator.data=device.operator
    form.imei.data=device.imei
    return render_template('admin/modifyDevice.html',form=form,device=device)

#查询设备
@admin.route('/queryDevice',methods=['GET','POST'])
def queryDevice():
    device_name=request.form['device_name']
    devices=Device.query.filter_by(device_name=device_name).all() 

    if devices:
        return render_template('admin/devicesList.html',list=devices)
    else:
        return "您查询的设备不存在"
